const localName = '__aniStore';
export class CreateStore {
    constructor(reducer, initialState) {
        this.reducer = reducer;
        this.state = initialState;
        this.listeners = [];
        this.loadState(); // 尝试从本地存储加载状态
        this.dispatch = this.dispatch.bind(this);
    }

    getState() {
        return this.state;
    }

    dispatch(action) {
        console.log(this)
        this.state = this.reducer(this.state, action);
        this.listeners.forEach(listener => listener());
        // this.saveState(); // 状态更新后保存到本地存储
    }

    subscribe(listener) {
        this.listeners.push(listener);
        return () => this.listeners = this.listeners.filter(l => l !== listener);
    }

    saveState() {
        wx.setStorageSync(localName, JSON.stringify(this.state));
    }

    loadState() {
        const savedState = wx.getStorageSync(localName);
        if (savedState) {
            this.state = { ...this.state, ...JSON.parse(savedState) };
            this.listeners.forEach(listener => listener()); // 通知所有订阅者状态已更新
        }
    }
}

// 用于将多个reducer合并成一个reducer
export function applyMiddleware(store, middlewares) {
    middlewares.slice().reverse().forEach(middleware => {
        store.dispatch = middleware(store)(store.dispatch);
    });
}

// 用于打印action和state的中间件
export function logger(store) {
    return function(next) {
        return function(action) {
            console.log('dispatching', action);
            let result = next(action);
            console.log('next state', store.getState());
            return result;
        };
    };
}

// 用于处理异步action的中间件
export function thunk(store) {
    return function(next) {
        return function(action) {
            if (typeof action === 'function') {
                return action(store.dispatch, store.getState);
            }
            return next(action);
        };
    };
}

// 用于将状态持久化到本地存储的中间件
export function persistMiddleware(store) {
    return function(next) {
        return function(action) {
            const result = next(action); // 先让 action 通过其他中间件和 reducer 处理
            const newState = store.getState(); // 获取更新后的状态
            wx.setStorageSync(localName, JSON.stringify(newState)); // 将新状态同步到本地存储
            return result;
        };
    };
}
